import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.*;
import java.util.LinkedHashMap;
import java.util.Map;
import javax.servlet.http.HttpSession;

@WebServlet(urlPatterns = {"/login"})
public class login extends HttpServlet {
    private static final long serialVersionUID = 1L;
    protected void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException {
        String URL = getServletContext().getInitParameter("db.url");
        String NAME = getServletContext().getInitParameter("db.user");
        String PASSWORD = getServletContext().getInitParameter("db.password");
        System.out.println(res.isCommitted());
        try (Connection conn = DriverManager.getConnection(URL, NAME, PASSWORD)) {
            String sqlQuery = "select username,familyname, name, email, passwd from user where username='" + req.getParameter("username") + "'";
            System.out.println(sqlQuery);
            Statement sqlStmt = conn.createStatement(java.sql.ResultSet.TYPE_SCROLL_INSENSITIVE, java.sql.ResultSet.CONCUR_READ_ONLY);

            ResultSet rs = sqlStmt.executeQuery("select * from user where username='" + req.getParameter("username") + "'");
            rs.next();
            System.out.println(rs.getString("username") + rs.getString("name"));

            sqlStmt.executeQuery(sqlQuery);
            ResultSet sqlResultSet = sqlStmt.getResultSet();
            sqlResultSet.next();
            Map<String, String> message = new LinkedHashMap<String, String>();
            message.put("用户名", sqlResultSet.getString("username"));
            message.put("姓", sqlResultSet.getString("familyname"));
            message.put("名", sqlResultSet.getString("name"));
            message.put("邮箱", sqlResultSet.getString("email"));
            HttpSession session = req.getSession(true);
            if(req.getParameter("net_auto_login") != null)
                session.setMaxInactiveInterval(7 * 24 * 60 * 60);
            session.setAttribute("Login", message);

	    DatabaseConnect db= new DatabaseConnect(getServletContext());
	    if(db.getimage(sqlResultSet.getString("username")) != null)
		session.setAttribute("portrait", db.getimage(sqlResultSet.getString("username")));

            session.setAttribute("username", sqlResultSet.getString("username"));
            res.sendRedirect("http://localhost:8080/profile.jsp");
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
